import 'package:flutter/material.dart';
import '../service/nfc_reader.dart';
import 'package:crypto/crypto.dart';
import 'package:convert/convert.dart';
import 'package:image_picker/image_picker.dart';
import 'webviewpage.dart';
class Test extends StatefulWidget {
  int index;
  Test({index});
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  String _result="";
  //1.	选择CA_APDU
  _scan() {
    NfcReader().instance.readSbk().then((result){
      print("readSbk:$result");
      setState(() {
        _result=result;
      });
    });
  }
  //私钥签名
  _scan_ca() {
    NfcReader().instance.signSbk('3DE741F445DD357BEA4E6C3FE643703638D30066D45821CE37DE7E38126739EF').then((result){
      print("signSbk:$result");
      setState(() {
        _result=result;
      });
    });
  }
  //sm4加密
  _scan_encry() {
    //[密钥，明文]
    encryBySm4('3DE741F445DD357BEA4E6C3FE6437036','3E76B1F9E955FC46DAE16BE1445BF3B6').then((result){
      print("cipher:$result");
      setState(() {
        _result=result.substring(0,32);
      });
    });
  }
  //打开Webview
  _openWebView(){
    String url="http://106.12.180.103/flutter02.html";
    Navigator.push(context, MaterialPageRoute(builder:(context) =>Webviewpage(url:url ,)));
  }
  //打开Webview
  _openWebView2(){
    String url="http://106.12.180.103/flutter01.html";
    Navigator.push(context, MaterialPageRoute(builder:(context) =>Webviewpage(url:url ,)));
  }
  _hashImage(){
    ImagePicker.pickImage(source: ImageSource.gallery,imageQuality:60).then((image){
      List<int> list= image.readAsBytesSync();
      var digest = sha256.convert(list);
      // 这里其实就是 digest.toString()
      String hexStr= hex.encode(digest.bytes);
      hexStr=hexStr.toUpperCase();
      setState(() {
        _result=hexStr;
      });
    });
  }
  //[密钥，明文]
 Future<String> encryBySm4(String key,String plainTextHex) async{
    //[密钥，明文]
    return await NfcReader().instance.encryptData_ECB([key,plainTextHex]);
  }
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text("测试"),
          centerTitle: true,
        ),
        body: Container(
          child: ListView(
            children: <Widget>[
              FlatButton(onPressed: _scan, child: Text("读卡信息")),
              FlatButton(onPressed: _scan_ca, child: Text("私钥签名")),
              FlatButton(onPressed: _scan_encry, child: Text("加密")),
              FlatButton(onPressed: _hashImage, child: Text("hash 图片")),
              FlatButton(onPressed: _openWebView, child: Text("打开webview测试")),
              FlatButton(onPressed: _openWebView2, child: Text("打开webview测试2")),
              Container(
                padding: EdgeInsets.only(left: 20,right: 20),
                child:Text(_result) ,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
